<?php

namespace App\Http\Controllers\Notify;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class NotifyController extends Controller
{
    public function index(Request $request)
    {
        Log::info('notify.index received post data', $request->post());
        return response('OK');
    }

    public function test(Request $request)
    {
        Log::info('notify.test received post data', $request->post());
        Log::info('notify.test received INPUT ' . file_get_contents('php://input'));
        //Log::info('DNS validate ' . ($this->validateDns() ? 1 : 0));
        return response('OK');
    }

    public function paypal(Request $request)
    {
        Log::info('notify.paypal received post data', $request->post());
        Log::info('notify.paypal received INPUT ' . file_get_contents('php://input'));
        return response('OK');
    }

    // 客户端证书验证
    private function validateSslCert()
    {
        $clientCertificate = $_SERVER['SSL_CLIENT_CERT'];
        // Worldpay的根证书内容
        $worldpayRootCertificate = file_get_contents('/path/to/worldpay-root-certificate.pem');;
        // 验证证书
        return openssl_x509_checkpurpose($clientCertificate, X509_PURPOSE_ANY, [$worldpayRootCertificate]);

    }

    // 反向dns验证
    private function validateDns(): bool
    {
        $clientIP = \request()->getClientIp();
        Log::info('DNS validateDns clientIP ' . $clientIP);
        $reverseDNS = gethostbyaddr($clientIP);
        Log::info('DNS validateDns reverseDNS ' . $reverseDNS);
        $expectedReverseDNS = '*.worldpay.com';
        return fnmatch($expectedReverseDNS, $reverseDNS);
    }
}
